//
//  UIApplication+Tool.m
//  LuxuryGoods
//
//  Created by 刘星辰 on 2018/5/19.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "UIApplication+Tool.h"

@implementation UIApplication (Tool)
/**
 获取当前真在显示的ViewController
 
 @return 获取当前真在显示的ViewController
 */
+ (UIViewController *)getCurViewController
{
    UIViewController *result = nil;
    
    UIWindow * window = [[self sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[self sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    if (window.subviews.count > 0) {
        UIView *frontView = [[window subviews] objectAtIndex:0];
        id nextResponder = [frontView nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            result = nextResponder;
        } else {
            result = window.rootViewController;
        }
    } else {
        result = window.rootViewController;
    }
    
    
    if ([result isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabVC = (UITabBarController *)result;
        UINavigationController *navVC =  tabVC.selectedViewController;
        return  [navVC.viewControllers lastObject];
    } else if ([result isKindOfClass:[UINavigationController class]]){
        UINavigationController *navVC = (UINavigationController *)result;
        return [navVC.viewControllers lastObject];
    }
    
    return result;
}

#pragma mark 跳转到设置界面
+ (void)openSettingPage
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }
    });
}

@end
